<script lang="ts" setup>
import {getCurrentInstance, onMounted, ref, watch} from "vue";
import KtTable from "../KtTable/KtTable.vue";
import KtTableCard from "./KtTableCard.vue";
import {ElMessageBox} from "element-plus";
import KtIcon from "../KtIcon/KtIcon.vue";

let props = defineProps({
  dataSource: {
    type: Object,
    default: null,
  },
  columns: {
    type: Array<any>,
    default: null,
  },
  pageSizes: {
    type: Array<any>,
    default: () => [10, 20, 30, 40, 50],
  },
  pageSize: {
    type: Number,
    default: 10,
  },
  pageNumber: {
    type: Number,
    default: 1,
  },
  total: {
    type: Number,
    default: 0,
  },
  pageRequestParam: {
    type: Object,
    default: null,
  },
  pageResult: {
    type: Object,
    default: null,
  },
  isIndexShow: {
    type: Boolean,
    default: true,
  },
  isHasSelection: {
    type: Boolean,
    default: true,
  },
  selection: {
    type: Array<any>,
    default: () => [],
  },
  rowKey: {
    type: String,
    default: "id",
  },
  border: {
    type: Boolean,
    default: false,
  },
  isHasAdd: {
    type: Boolean,
    default: true,
  },
  isHasRemove: {
    type: Boolean,
    default: true,
  },
});

let propsData = ref({
  dataSource: props.dataSource,
  columns: props.columns,
  pageSizes: props.pageSizes,
  pageSize: props.pageSize,
  pageNumber: props.pageNumber,
  total: props.total,
  pageRequestParam: props.pageRequestParam,
  pageResult: props.pageResult,
  isIndexShow: props.isIndexShow,
  isHasSelection: props.isHasSelection,
  selection: props.selection,
  rowKey: props.rowKey,
  border: props.border,
  isHasAdd: props.isHasAdd,
  isHasRemove: props.isHasRemove,
});
// let emit = defineEmits(["change","update:selection"]);
let instance = getCurrentInstance();
let emit = instance?.emit;

let setData = () => {
  if (propsData.value.pageResult) {
    propsData.value.dataSource = props.pageResult.content;
    propsData.value.total = props.pageResult.totalElements;
  }
  if (propsData.value.pageRequestParam) {
    propsData.value.pageSize = props.pageRequestParam.pageSize;
    propsData.value.pageNumber = props.pageRequestParam.pageNumber;
  }
}

setData();
// 监听selection
watch(() => propsData.value.selection, () => {
  console.log("selection");
  emit?.("update:selection", propsData.value.selection);
});


watch(() => props.pageResult, () => {
  setData();
});

watch(() => props.pageSize, () => {
  if (propsData.value.pageRequestParam) {
    props.pageRequestParam.pageSize = props.pageSize;
  }
});

watch(() => props.pageNumber, () => {
  if (propsData.value.pageRequestParam) {
    props.pageRequestParam.pageNumber = props.pageNumber;
  }
});


let changePageNumber = (val: any) => {
  propsData.value.pageNumber = val;
  // 修改父组件的值
  if (propsData.value.pageRequestParam) {
    propsData.value.pageRequestParam.pageNumber = val;
  }

  emit?.("change");

};

let changePageSize = (val: any) => {
  propsData.value.pageSize = val;
  if (propsData.value.pageRequestParam) {
    propsData.value.pageRequestParam.pageSize = propsData.value.pageSize;
  }
  emit?.("change");
};

let toEmit = (emitName: any, param: any) => {
  emit?.(emitName, param);
}

let ktTable = ref();


let setLoading = (val: boolean) => {
  ktTable.value.setLoading(val);
}

// propsData.selection.length
let getSelectionLength = () => {
  return propsData.value.selection.length;
}

let toRemoveClick = () => {
  if (propsData.value.selection.length == 0) {
    ElMessageBox.alert("请先选择", "提示", {
      confirmButtonText: "确定",
    });
    return;
  }
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    toEmit("remove", propsData.value.selection);
  }).catch(() => {
  });
}

let toAddClick = () => {
  emit?.("add");
}

let selectSelection = (selection: any) => {
  ktTable.value.selectSelection(selection);
}

let height = ref(0);


let headerShow = ref(true);

let hasHeaderOCBtn = ref(false);

onMounted(() => {
  let cardHeader = document.getElementById("cardHeader");
  if (cardHeader) {
    height.value = `calc(100vh - ${cardHeader.clientHeight}px - 50px)`;
  }

  // 获取cardHeaderTop的高度
  let cardHeaderTop = document.getElementById("cardHeaderTop");
  // 如果高度小于20px，则不显示展开收起按钮
  if (cardHeaderTop) {
    if (cardHeaderTop.clientHeight > 20) {
      hasHeaderOCBtn.value = true;
    }
  }
});
// 监听headerShow变化
watch(() => headerShow.value, () => {
  setTimeout(()=>{
    let cardHeader = document.getElementById("cardHeader");
    if (cardHeader) {
      height.value = `calc(100vh - ${cardHeader.clientHeight}px - 50px)`;
    }
  },500);
});


/**
 * 暴露给父组件的方法
 */
defineExpose({
  setLoading,
  selectSelection
});

</script>

<template>
  <el-card>
    <div id="cardHeader">
      <div
          v-show="headerShow"
      id="cardHeaderTop"
      >
        <slot name="header"></slot>
      </div>
<!--   展开   -->
      <div
      v-if="hasHeaderOCBtn"
      >
      <div
          v-if="headerShow"
          @click="headerShow = false"
          style="cursor: pointer;font-size: 14px;text-align: right">
        <kt-icon type="primary"
                 size="14"
                 icon="el-icon-arrow-up-bold" ></kt-icon>
        <span style="font-size: 14px">收起</span>
      </div>
      <div
          v-if="!headerShow"
          @click="headerShow = true"
          style="cursor: pointer;font-size: 14px;text-align: right">
        <kt-icon type="primary"
                 size="14"
                 icon="el-icon-arrow-down-bold" ></kt-icon>
        <span style="font-size: 14px">展开</span>
      </div>

      </div>


      <div style="height: 10px"></div>
      <div>
        <div class="display-box">
          <div>
            <kt-icon class="refresh" type="primary" icon="el-icon-refresh" @click="emit?.('change')">刷新</kt-icon>
            <el-tag type="info">共 {{ propsData.total }} 条</el-tag>
            <el-tag v-if="getSelectionLength()>0"
                    style="margin-left: 10px"
                    type="info">已选 {{ getSelectionLength() }} 条</el-tag>
          </div>
          <div>
            <el-button
                v-if="propsData.isHasAdd"
                type="info"
                       @click="toAddClick">
              <kt-icon icon="el-icon-plus"></kt-icon>
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                        v-if="propsData.isHasRemove"
                       :disabled="propsData.selection.length==0"
                       @click="toRemoveClick">
              <kt-icon icon="el-icon-delete"></kt-icon>
            </el-button>
            <slot name="buttonBox"></slot>
          </div>
        </div>
      </div>
    </div>
    <div style="height: 10px"></div>

    <kt-table
        :border="border"
        ref="ktTable"
        :height="height"
        @toEmit="toEmit"
        v-model:selection="propsData.selection"
        :is-has-selection="isHasSelection"
        :row-key="rowKey"
        :columns="propsData.columns"
        :dataSource="propsData.dataSource"
        :is-index-show="propsData.isIndexShow">
      <slot></slot>
      <template #rightOption>
        <slot name="rightOption"></slot>
      </template>
    </kt-table>
    <div style="height: 20px"></div>
    <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="propsData.pageSizes"
        :total="propsData.total"
        :page-size="propsData.pageSize"
        :current-page="propsData.pageNumber"
        @size-change="changePageSize"
        @current-change="changePageNumber"
    />
  </el-card>
</template>

<style scoped>

</style>